import { IFeidaoAiNodejsComponent } from '@feidao/web/interfaces';

import render from '@feidao/web/atom/nodejs/render/render';
import nodejs from '@feidao/web/atom/nodejs/msg-b/nodejs';

import server_render from '../atom-n/server-render';
import { Params } from '../atom/params2query';
import p2q from '../atom/params2query';
import generate_query4render from '../atom/generate-query4render';
import generate_sort_fields from '../atom/generate-sort-fields';

import P01 from './P01';
import P02 from './P02';
import P04 from './P04';
import P03 from './P03';
import P05 from './P05';

const name2title = {
	'staff_name': '员工姓名',
	'staff_type': '员工类型',
	'deptname': '部门名称',
	'destination': '前往国家/地区',
	'to': '出境目的',
	'depart_time': '出境时间',
	'plan_time': '计划回国时间',
	'actual_time': '实际回国时间',
	'fund_source': '费用来源',
	'exit_port': '出境口岸',
	'antry_port': '入境口岸',
	'traffic_tool': '交通工具'
	// 'staff_no': '员工编号',
	// 'deptid': '部门编号',
	// '_id': 'id'
};

function create_data_sort(fd: IFeidaoAiNodejsComponent) {
	try {
		const fields = ['staff_name', 'staff_type','deptname',  'destination', 'to', 'depart_time', 'plan_time', 'actual_time','fund_source','exit_port','antry_port','traffic_tool'];
		const params = fd.data.params;
		delete params['page-no'];
		const data = generate_sort_fields(fd.data.url, fd.data.params as Params, fields);
		data.forEach((d) => {
			const field = d.field;
			render(fd.data.node, d, P02, field);
		});
	} catch (err) {
		console.error('------err', err);
	}
}

export default async function nba001(fd: IFeidaoAiNodejsComponent, ...args: any[]) {
	let page_no = fd.data.params['page-no'];
	if (!page_no) {
		page_no = 1;
	}
	let page_size = fd.data.params['page_size'];
	if (!page_size) {
		page_size = 20;
	}
	const q = p2q(fd.data.params as Params);
	const query = {
		filter: q.criteria,
		sort: q.sort,
		page_no,
		page_size
	};
	const data = generate_query4render(fd.data.url, fd.data.params as Params, name2title);
	render(fd.data.node, data, P01, 'P01');

	// 排序
	create_data_sort(fd);
	// 没有数据
	const res = await nodejs(fd.data.spaceid, "exit_record_find", query);
	// 无数据渲染P04
	if (res.dataArray.length == 0) {
		server_render(fd.data.node, 'P04', P04, '');
	} else {
		server_render(fd.data.node, 'P03', P03, res.dataArray);
	}

	res['page_size'] = page_size;
	render(fd.data.node, res, P05, 'P05');
}